﻿using System;
using System.Collections.Generic;
using System.Windows.Forms;
using Kimgwajang.MidnightPeach.Schema;

namespace Kimgwajang.MidnightPeach.Forms
{
    public partial class TableForm : Form
    {
        private readonly Database _database;

        private readonly string _dbmlPath;

        private bool _allTemplatesSelected;

        public TableForm()
        {
            InitializeComponent();
        }

        public TableForm(Database database, string dbmlPath) : this()
        {
            _database = database;
            _dbmlPath = dbmlPath;
        }

        protected override void OnShown(EventArgs e)
        {
            base.OnShown(e);

            bdsTable.DataSource = _database.Tables;

            SelectAllRows(true);

            btnOK.Focus();
        }

        private void SelectAllRows(bool selected)
        {
            foreach (DataGridViewRow row in dgvTable.Rows)
                row.Cells["colSelected"].Value = selected;
        }

        private void dgvVariable_ColumnHeaderMouseClick(object sender, DataGridViewCellMouseEventArgs e)
        {
            SelectAllRows(_allTemplatesSelected);
            _allTemplatesSelected = !_allTemplatesSelected;
        }

        private void btnOK_Click(object sender, EventArgs e)
        {
            var unselectedTables = RemoveUnselectedTemplates();

            bool allUpdatable = CheckUnupdatableTypes(unselectedTables);

            if (allUpdatable)
                DialogResult = DialogResult.OK;
            Close();
        }

        private List<Table> RemoveUnselectedTemplates()
        {
            dgvTable.EndEdit();

            var unselectedTables = new List<Table>();

            foreach (DataGridViewRow row in dgvTable.Rows)
            {
                bool selected = (bool)row.Cells["colSelected"].Value;

                if (selected == false)
                {
                    Table table = (Table) row.DataBoundItem;
                    unselectedTables.Add(table);
                }
            }

            _database.Tables.RemoveAll(unselectedTables.Contains);

            return unselectedTables;
        }

        private bool CheckUnupdatableTypes(List<Table> unselectedTables)
        {
            var unupdatables = SchemaExtractor.GetUnupdatableTypes(_dbmlPath, unselectedTables);
            if (unupdatables.Count > 0)
            {
                var form = new DbmlWarningForm(_dbmlPath, unupdatables);

                return form.ShowDialog() == DialogResult.OK;
            }

            return true;
        }
    }
}